﻿using KingsSharp.Common.Extensions;
using KingsSharp.Common.Secutiry;
using KingsSharp.Core.Data.Entity;
using CRM.Admin.Contracts.Contract.Logs;
using CRM.Admin.Contracts.Contract.Sys;
using CRM.Admin.Contracts.Dto.Logs;
using CRM.Admin.Contracts.Dto.Sys;
using CRM.Admin.Contracts.Model.Sys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace CRM.Admin.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 用户业务契约
        /// </summary>
        public IUserInfoService UserInfoService { get; set; }

        /// <summary>
        /// 登陆日志契约
        /// </summary>
        public ILoginLogService LoginLogService { get; set; }
       
        public ActionResult Index()
        {
           
            //var userdto = _userInfoService.ItemUserInfo.Where(a => a.LoginCode == AppVariable.UserData.LoginCode)
            //       .FirstOrDefault();
            //ViewBag.PortraitURL = "";
            //if (userdto != null)
            //{
            //    ViewBag.PortraitURL = userdto.PortraitURL;
            //}
            //short type = 10;
            //if (AppVariable.UserData.LoginCommID != 0)
            //{
            //    type = 20;
            //}
            //var corpDto = CorpItem.Instance[AppVariable.LoginCorpNumber];

            //var power = CorpPowerService.ItemCorpPower.Include(a => a.Menus).Include(a => a.MenuCatalogs)
            //    .Where(a => a.Id == corpDto.CorpPowerId).FirstOrDefault();
            var mList = MenuItem.Instance.GetCatalogTree();
            List<MenuCatalog> newmList = new List<MenuCatalog>();

            var nodeids = UserInfoService.GetUserMenuCatalogs(AppVariable.UserData.UserId);
            foreach (var one in mList)
            {
                if (one.Menus != null && one.Menus.Count(s => nodeids.Contains(s.Id)) > 0)
                {
                    var authids = nodeids.Intersect(one.Menus.Select(a => a.Id).ToArray());
                    one.Menus = one.Menus.Where(s => authids.Contains(s.Id)).ToList();
                    newmList.Add(one);
                }
            }
            newmList.OrderBy(a => a.Order);
            ViewBag.MenuJson = newmList.OrderBy(a => a.Order).ToJsonString();
            return View(newmList);
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string username, string password)
        {
            string resultstring = "";
            UserInfo user = UserInfoService.ItemUserInfo.Where(entity => entity.LoginCode == username).FirstOrDefault();
            if (user == null)
            {
                resultstring = "账号不存在";
            }
            else if (DesHelper.Encrypt(password, AppConsts.DES_USER_KEY) != user.Password)
            {
                resultstring = "密码不正确";
            }
            else
            {
                resultstring = "成功登录";
                UserCookies usercookie = new UserCookies();
                usercookie.UserName = user.Name;
                usercookie.UserId = user.Id;
                usercookie.LoginCode = user.LoginCode;
                string _usercookiestring = usercookie.ToJsonString();
                FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, user.Name, DateTime.Now,
                    DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes), false, _usercookiestring, "");
                string HashTicket = FormsAuthentication.Encrypt(Ticket);
                HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
                UserCookie.Path = FormsAuthentication.FormsCookiePath;
            
                UserCookie.Expires = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
                Response.Cookies.Add(UserCookie);

                UserInfoDto userdto = user.MapTo<UserInfoDto>();
                userdto.LastLoginIp = Request.GetIp();
                userdto.Browser = Request.GetBrowserName();
                //userdto.LastLoginDate = DateTime.Now.ToString();
                //UserInfoService.UpdateUserInfo(userdto);
                UserInfoService.UpdateLastLoginData(userdto);


                LoginLogDto loginlog = new LoginLogDto()
                {
                    Id = Guid.NewGuid(),
                    Action = "登陆系统",
                    Browser = userdto.Browser,
                    Ip = userdto.LastLoginIp,
                    LoginCode = userdto.LoginCode,
                    Name = userdto.Name,
                    SystemName = Request.GetSystemName()
                };
                LoginLogService.InsertLoginlog(loginlog);

                if (Request["ReturnUrl"] != null && Request["ReturnUrl"].ToString() != "")
                {
                    Response.Redirect(FormsAuthentication.GetRedirectUrl(user.Name, true));
                }
                else
                {
                    Response.Redirect("~/Home/Index");
                }
            }
            ViewBag.Error = resultstring;
            return View();
        }
        /// <summary>
        /// 退出登陆
        /// </summary>
        public void LoginOut()
        {
            Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            FormsAuthentication.SignOut();
            Session.Abandon();

            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);
            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);
            // FormsAuthentication.RedirectToLoginPage();

            Response.Redirect("~/Home/Login");
        }
    }
}